package com.google.code.toub.waves.editor.util;

import com.google.code.toub.waves.editor.annotation.AnnotationColor;
import com.google.wave.api.Annotation;
import com.google.wave.api.Blip;
import com.google.wave.api.BlipContentRefs;
import com.google.wave.api.Wavelet;

/**
 * Blip editor
 * 
 * @author ntoublanc
 * 
 */
public class BlipEditor {
	/**
	 * Line separator ("\n").
	 */
	public static final String LINE_SEPARATOR = "\n";

	/**
	 * Reply to the wavelet with the specified message.
	 * 
	 * @param wavelet
	 *            wavelet
	 * @param message
	 *            message
	 */
	public void reply(Wavelet wavelet, String message) {
		this.reply(wavelet, message, (AnnotationColor) null);
	}

	/**
	 * Reply to the wavelet with the specified message.
	 * 
	 * @param wavelet
	 *            wavelet
	 * @param message
	 *            message
	 * @param color
	 *            color
	 */
	public void reply(Wavelet wavelet, String message, AnnotationColor color) {
		// create a new blip with the message content
		Blip blip = wavelet.reply(LINE_SEPARATOR + message);
		if (color != null) {
			// format the message using the specified color
			blip.all().annotate(Annotation.COLOR, color.getAnnotationValue());
		}
	}

	/**
	 * Append text to blip
	 * 
	 * @param blip
	 * @param message
	 */
	public void append(Blip blip, String message, String... annotationKeys) {
		append(blip, message, (AnnotationColor) null, annotationKeys);
	}

	/**
	 * Append text to blip
	 * 
	 * @param blip
	 * @param message
	 * @param color
	 */
	public void append(Blip blip, String message, AnnotationColor color,
			String... annotationKeys) {
		if (blip != null) {
			// add expiration date
			int start = blip.length() + 1;

			blip.append(LINE_SEPARATOR + message);

			int end = blip.length();

			BlipContentRefs messageRange = blip.range(start, end);
			if (color != null) {
				// format the message using the specified color
				messageRange.annotate(Annotation.COLOR, color
						.getAnnotationValue());
			}
			if (annotationKeys != null) {
				// annotate the appended text with the specified annotations
				for (String annotationKey : annotationKeys) {
					messageRange.annotate(annotationKey);
				}
			}
			// add a space
			blip.append(" ");
			BlipContentRefs spaceRange = blip.range(end, end + 1);
			spaceRange.clearAnnotation(Annotation.COLOR);
			if (annotationKeys != null) {
				// clear the annotations to the appended text
				for (String annotationKey : annotationKeys) {
					spaceRange.clearAnnotation(annotationKey);
				}
			}
		}
	}
}
